#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) Anton A Nesterov
# License: Apache2.0


from handlers import obj
from .config import app
from bottle import request, response, abort
from model.upload import Collection, File



################################################################################

#get collection list
@app.get('/uploads/collections')
def collection_list():
  return {"data":Collection.lst(**request.GET)}

# create the collection
@app.post('/uploads/collection')
def new_collection():

  title = request.json.get('title')
  old = Collection.get(title)

  if not old:
    Collection.create(title)
    return {}

  else:
    abort(409)

@app.delete('/uploads/collection/<id>')
def del_collection(id):

  File.rem_collection(id)
  abort(204)

@app.put('/uploads/collection')
def up_collection():

  Collection.put(**request.json)

  return {}

################################################################################
#Files

@app.get('/uploads')
def file_list():

  data = request.GET
  lst = File.lst(**data)

  ls = []
  for i in lst:

    key = i.thumb_100 and i.thumb_100.key()
    if key:
      thumb = '../upload/%s' % i.thumb_250.key() ## see upload handlers
    else:
      thumb = '../static/img/%s.png'%i.title.split('.')[-1]

    collect = ''
    if i.colle:
      collect = i.colle.title

    ls += [{
      "id":str(i.key().id_or_name()),
      "title":unicode(i.title).encode('utf-8'),
      "collection":unicode(collect).encode('utf-8'),
      "thumb": thumb
    }]

  return {"data":ls}

@app.delete('/uploads/<id>')
def delete_file(id):
  File.rem(id)
  return {}

@app.get('/uploads/download-session/<id>')
def download(id):
  stuff = File.get_by_id(long(id))

  if stuff and stuff.blob_key.key():
    return "../upload/%s" % stuff.blob_key.key()

  abort(404)


################################################################################
## UPLOAD HANDLERS

import webapp2
import urllib
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import images, files
from google.appengine.api import users

@app.get('/uploads/session')
def get_session():

    if not users.is_current_user_admin():
      abort(403)
  return blobstore.create_upload_url('/upload/')

class Uploader(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):

    if not users.is_current_user_admin():
      abort(403)


   upload_files = self.get_uploads('file')
   assert len(upload_files)

   for blob_info in upload_files:

    thumb_400 = None
    thumb_250 = None
    thumb_100 = None

    imgs = ['jpg','jpeg','JPG','JPEG','png','PNG','gif','GIF']
    if blob_info.filename.split('.')[-1] in imgs:
      reader = blob_info.open()
      img = images.Image(reader.read())

      img.resize(height=400)
      thumb_400 = files.blobstore.create(mime_type='image/png',
                                _blobinfo_uploaded_filename=blob_info.filename)
      with files.open(thumb_400, 'a') as f:
	      f.write(img.execute_transforms(output_encoding=images.PNG))
      files.finalize(thumb_400)

      img.resize(height=250)
      thumb_250 = files.blobstore.create(mime_type='image/png',
                                _blobinfo_uploaded_filename=blob_info.filename)
      with files.open(thumb_250, 'a') as f:
	      f.write(img.execute_transforms(output_encoding=images.PNG))
      files.finalize(thumb_250)

      img.resize(height=100)
      thumb_100 = files.blobstore.create(mime_type='image/png', _blobinfo_uploaded_filename=blob_info.filename)
      with files.open(thumb_100, 'a') as f:
	      f.write(img.execute_transforms(output_encoding=images.PNG))
      files.finalize(thumb_100)

    File.put(  title = str(blob_info.filename).decode("UTF-8") ,
               colle = Collection.get_or_put( self.request.get('collection') ),
	             thumb_100 =thumb_100 and files.blobstore.get_blob_key(thumb_100) or None,
               thumb_250 =thumb_250 and files.blobstore.get_blob_key(thumb_250) or None,
	             thumb_400 = thumb_400 and files.blobstore.get_blob_key(thumb_400) or None,
               blob_key  = blob_info.key()
             )


class FileServe(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, resource):
    if not resource:
      return
    resource = str(urllib.unquote(resource))
    blob_info = blobstore.BlobInfo.get(resource)
    self.send_blob(blob_info)

uploader = webapp2.WSGIApplication([
  ('/upload/', Uploader),
  ('/upload/([^/]+)?', FileServe)
])

